<?php
/**
 * 留言板类
 */
class Msg 
{
	
	public function is_login()
	{
		if(isset($_SESSION['user'])){
			return true;
		}else{
			return false;
		}
	}
	
	public function show()
	{

		$db = new Db('msg');

		$total = $db->count();
		// 总数

		// 每页多少条
		$num = 2;
		//  一共多少页
		$pages = ceil($total/$num);
		// 当前在第几页
		$p = isset($_GET['p']) ? $_GET['p'] : 1;


		$sql = "select t1.*,t2.username from msg t1 inner join user t2 on t1.uid=t2.user_id order by msg_id desc limit ".($p-1)*$num.",".$num;

		$oldData = $db->query($sql);

		// 计算开始值与结束值 
		if($p<3){
			$start = 1;
			$end = 5;
		}elseif($p>($pages-2)){
			$start = $pages-4;
			$end = $pages;
		}else{
			$start = $p-2;
			$end = $p+2;
		}

		include './template/index.html';
		
	}

	public function getMore()
	{
		// 总数
		$total = count($this->oldData);
		// 每页多少条
		$num = 2;
		//  一共多少页
		$pages = ceil($total/$num);
		// 当前在第几页
		$p = isset($_POST['p']) ? $_POST['p'] : 1;

		// 截取数组的某一个部分
		$oldData = array_slice($this->oldData, ($p-1)*$num,$num,true);

		if($oldData){
			exit(json_encode(['error'=>0,'data'=>$oldData]));
		}else{
			exit(json_encode(['error'=>1,'info'=>"没有更多数据了"]));
		}

		
	}

	public function add($value='')
	{
		if(!$this->is_login()){
			$this->web_error('你还有登录');
		}
		// 接收post过来的数据
		$data = $_POST;
		// 增加创建时间
		$data['create_time'] = time();

		$data['uid'] = $_SESSION['user']['user_id'];

		$db = new Db('msg');

		$db->insert($data);
		// 跳转
		$this->ok();

	}

	public function web_error($info)
	{
		include './template/error.html';
		exit;
	}
	public function del($value='')
	{

		if(!$this->is_login()){
			$this->web_error('你还有登录');
		}

		$id = $_GET['id'];

		$db = new Db('msg');

		$db->where("msg_id='{$id}'");

		$db->delete();
		// 跳转
		$this->ok();
		
	}


	public function ok()
	{
		header("Location:./index.php");
	}

	public function edit()
	{

		if(!$this->is_login()){
			$this->web_error('你还有登录');
		}
		
		$id = $_GET['id'];

		$db = new Db('msg');

		$db->where("msg_id='{$id}'");

		$msg = $db->select();

		$one = current($msg);

		include './template/edit.html';
	}

	public function save()
	{
		// 接收post过来的数据
		$data = $_POST;

		$id = $_GET['id'];

		$db = new Db('msg');

		$db->where("msg_id='{$id}'");

		$db->update($data);
		// 跳转
		$this->ok();
	}
}